package com.example;

import com.example.mapper.EmployeeMapper;
import com.example.pojo.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import org.junit.jupiter.api.Test;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;

public class MyBatisTest {
    
    @Test
    public void testAllOperations() throws Exception {
        // 1. 加载配置文件
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        
        // 2. 创建 SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        
        try (SqlSession session = factory.openSession()) {
            // 3. 获取 Mapper 接口实例
            EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
            
            // 测试查询所有
            List<Employee> employees = mapper.selectAll();
            employees.forEach(System.out::println);
            
            // 测试添加数据
            Employee newEmp = new Employee();
            newEmp.setName("张三");
            newEmp.setSal(new BigDecimal("15000.00"));
            newEmp.setDept("技术部");
            mapper.insert(newEmp);
            session.commit();  // 提交事务
            
            // 测试修改薪资
            mapper.updateSalById(1, new BigDecimal("20000.00"));
            session.commit();
            
            // 测试删除
            mapper.deleteById(5);
            session.commit();
        }
    }
}